package com.darchrow.nio.file;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;

/**
 * @author mdl
 * @date 2020/5/26 16:26
 */
public class NIOReadFileTest {

    private static void read(File source) throws Exception {

        RandomAccessFile read = new RandomAccessFile(source, "rw");
        FileChannel readChannel = read.getChannel();

        char[] bytes =new char[1024];
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        int len = 0;
        while ((len = readChannel.read(byteBuffer)) > 0) {

            byteBuffer.flip();

//            CharBuffer charBuffer = CharBuffer.allocate(1024);
//            Charset charset = Charset.forName("UTF-8");
//            CharsetDecoder decoder = charset.newDecoder();
//            decoder.decode(byteBuffer, charBuffer, true);
//            charBuffer.flip();


            System.out.print(Charset.forName("utf-8").decode(byteBuffer));


//            char[] array = charBuffer.array();
//            System.out.println(new String(array));

            byteBuffer.clear();
        }
        readChannel.close();
        read.close();
    }


    public static void main(String[] args) throws Exception {
        File file = new File("D:\\selfstudy\\tmp.txt");
        read(file);

    }

}
